package com.szp.drug.component.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.szp.drug.component.mapper.DrugCheckMapper;
import com.szp.drug.component.service.api.DrugCheckService;
import com.szp.drug.entity.DrugCheck;
import com.szp.drug.util.ResultEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 体检实现类
 * @author SuZePing
 * @create 2021-03-07 12:27
 * @E-mail suzeping10@126.com
 */
@Slf4j
@Service
public class DrugCheckServiceImpl extends ServiceImpl<DrugCheckMapper, DrugCheck> implements DrugCheckService {

	@Autowired
	private DrugCheckMapper checkMapper;

	/**
	 * 分页获取体检记录
	 * @param checkName
	 * @param pageNum
	 * @param pageSize
	 * @return
	 */
	@Override
	public ResultEntity<PageInfo<DrugCheck>> getPageInfo(String checkName, String pageNum, String pageSize) {
		// 开启分页
		PageHelper.startPage(Integer.parseInt(pageNum),Integer.parseInt(pageSize));
		QueryWrapper<DrugCheck> wrapper = new QueryWrapper<>();
		wrapper.eq("deleted","0");
		wrapper.and(m -> m.like("check_name",checkName))
				.orderByAsc("check_time");
		List<DrugCheck> checks = checkMapper.selectList(wrapper);
		log.debug("返回 checks:{}",checks);
		return ResultEntity.success(new PageInfo<>(checks));
	}

	/**
	 * 新增体检记录
	 * @param check
	 * @return
	 */
	@Override
	public ResultEntity<Integer> saveCheck(DrugCheck check) {
		check.setCheckId("CH" + IdUtil.fastSimpleUUID().substring(0, 10))
				.setCheckTime(DateUtil.now());
		checkMapper.insert(check);
		// 返回新增后总数量 为数据展示页码使用
		QueryWrapper<DrugCheck> checkWrapper = new QueryWrapper<>();
		checkWrapper.eq("deleted","0");
		Integer count = checkMapper.selectCount(checkWrapper);
		return ResultEntity.success(count);
	}

	/**
	 * 删除记录
	 * @param checkId
	 * @return
	 */
	@Override
	public ResultEntity<String> removeCheck(String checkId) {
		if (StrUtil.hasEmpty(checkId)){
			return ResultEntity.error("主键id不能为空!");
		}
		DrugCheck check = new DrugCheck();
		check.setCheckId(checkId).setDeleted("1");
		checkMapper.updateById(check);
		return ResultEntity.success();
	}
}
